//
//  EtcViewController.m
//  NewPro
//
//  Created by RYX on 2019/7/24.
//  Copyright © 2019 何荧红. All rights reserved.
//

#import "EtcViewController.h"
#import <WebKit/WebKit.h>
#import "UINavigationBar+handle.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterfaceObject.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import "WXApi.h"
#import "HomeList.h"
#import "RecommendModel.h"
#import "CreditCardStore.h"

@interface EtcViewController ()<WKNavigationDelegate,WKUIDelegate>
{
    NSString *utf8String;
    NSString *title;
    NSString *description;
    NSString *previewImageUrl;
}
@property (nonatomic,strong) UIView *bgView;
@property (nonatomic, strong) UIView *shareView;
@property (nonatomic,strong) WKWebView *webView;
@property (nonatomic, strong) UIProgressView *myProgressView;


@end

@implementation EtcViewController

- (UIView *)bgView{
    
    if (!_bgView) {
        
        _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        _bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        [_bgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didBgView)]];
    }
    
    return _bgView;
}

- (void)didBgView{
    
    MJWeakSelf
    [UIView animateWithDuration:0.2 animations:^{
        
        weakSelf.shareView.y = SCREEN_HEIGHT + 50;
        weakSelf.bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
        
    } completion:^(BOOL finished) {
        
        [weakSelf.bgView removeFromSuperview];
    }];
    
}

- (UIView *)shareView{
    
    if (!_shareView) {
        
        _shareView = [[[NSBundle mainBundle] loadNibNamed:@"RedShareView" owner:self options:nil] objectAtIndex:0];
        _shareView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 105);
        _shareView.y = SCREEN_HEIGHT + 50;
    }
    
    return _shareView;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [self.navigationController.navigationBar navBarBackGroundColor:BLUECOLOR image:nil isOpaque:YES];
}

- (WKWebView *)webView{
    
    if (!_webView) {
        
        _webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
        [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
        NSString *url = [HomeList sharedInstance].recommendModel.link;
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
        [_webView loadRequest:request];
    }
    
    return _webView;
}

- (UIProgressView *)myProgressView {
    
    if (_myProgressView == nil) {
        
        _myProgressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0)];
        _myProgressView.tintColor = BLUECOLOR;
        _myProgressView.trackTintColor = BASECOLOR;
        
    }
    
    return _myProgressView;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.autoresizesSubviews = NO;
    
    [self setNavBar];
        
    [self.view addSubview:self.webView];
    [self.view addSubview:self.myProgressView];
    [self.view addSubview:self.shareView];
    
    MJWeakSelf
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(weakSelf.view);
        
    }];
}

#pragma mark - 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"]) {
        
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        self.myProgressView.alpha = 1.0f;
        [self.myProgressView setProgress:newprogress animated:YES];
        if (newprogress >= 1.0f) {
            
            [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                
                self.myProgressView.alpha = 0.0f;
                
            } completion:^(BOOL finished) {
                
                [self.myProgressView setProgress:0 animated:NO];
                
            }];
            
        }
        
    } else {
        
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        
    }
    
}

- (void)dealloc{
    
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    
}

- (void)setNavBar{
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //修改按钮向右偏移10 point
    [rightBtn setFrame:CGRectMake(14, 0.0, 44.0, 44.0)];
    //修改方法
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 44.0, 44.0)];
    [view addSubview:rightBtn];
    [rightBtn addTarget:self action:@selector(onRightBtn) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setImage:[UIImage imageNamed:@"分享"] forState:UIControlStateNormal];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:view];
    self.navigationItem.rightBarButtonItem = item;
}

- (void)onRightBtn{
    
    if (self.shareView.y >= ScreenHeight){
        
        [self.view insertSubview:self.bgView belowSubview:self.shareView];
        
        MJWeakSelf
        [UIView animateWithDuration:0.7 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0.5 options:0 animations:^{
            
            weakSelf.shareView.y = SCREEN_HEIGHT - 105 - iPhoneX_Top;
            weakSelf.bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
            
        } completion:nil];
        
    }else{
        
        
        [self didBgView];
        
    }
}

- (IBAction)onShareWX:(UIButton *)sender {
    
    [self getShareNoWithFlat:@"微信好友" andSender:sender];
    
}
- (IBAction)onSharePYQ:(UIButton *)sender {
    
    [self getShareNoWithFlat:@"微信朋友圈" andSender:sender];
    
}
- (IBAction)onShareQQ:(UIButton *)sender {
    
    [self getShareNoWithFlat:@"QQ好友" andSender:sender];
}
- (IBAction)onShareKJ:(UIButton *)sender {
    
    [self getShareNoWithFlat:@"空间" andSender:sender];
}


- (void)getShareNoWithFlat:(NSString *)flat andSender:(UIButton *)sender{
    
    MJWeakSelf
    CreditCardStore *store = [[CreditCardStore alloc] init];
    [store getShareNoWithFlat:flat andShareTo:nil andType:@"2" success:^(NSString *shareNo) {
        
        [weakSelf shareWithFlat:flat andShareNo:shareNo];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            sender.enabled = YES;
        });
        
    } failure:^(NSError *error) {
        
        sender.enabled = YES;
        [weakSelf showMBPError:[HttpTool handleError:error]];
    }];
    
}

- (void)shareWithFlat:(NSString *)flat andShareNo:(NSString *)shareNo{
    
    NSString *title = [HomeList sharedInstance].recommendModel.name;
    NSString *content = [HomeList sharedInstance].recommendModel.comment;
    NSString *imgUrl = [HomeList sharedInstance].recommendModel.smallImg;
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];
    UIImage *img = [UIImage imageWithData:data];
    NSString *url = [NSString stringWithFormat:@"%@?shareNo=%@&customId=%@&pId=%@&isShow=1",[HomeList sharedInstance].recommendModel.link,shareNo,[UserDefaultsManager sharedInstance].user_id,[HomeList sharedInstance].recommendModel.uid];
    
    if ([flat isEqualToString:@"微信好友"]) {
        
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = title;//主标题
        message.description = content;//描述
        [message setThumbImage:[ImgManager getSimpleImg:img]];
        
        WXWebpageObject *webobject = [WXWebpageObject object];
        webobject.webpageUrl = url;
        message.mediaObject = webobject;
        
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc]init];
        req.message = message;
        req.scene = WXSceneSession;
        [WXApi sendReq:req];
    }else if ([flat isEqualToString:@"微信朋友圈"]){
        
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = title;//主标题
        message.description = content;//描述
        [message setThumbImage:[ImgManager getSimpleImg:img]];
        
        WXWebpageObject *webobject = [WXWebpageObject object];
        webobject.webpageUrl = url;
        message.mediaObject = webobject;
        
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc]init];
        req.message = message;
        req.scene = WXSceneTimeline;
        [WXApi sendReq:req];
    }else if ([flat isEqualToString:@"QQ好友"]){
        
        QQApiTextObject *txtObj = [QQApiNewsObject objectWithURL:[NSURL URLWithString:url] title:title description:content previewImageURL:[NSURL URLWithString:imgUrl]];
        
        SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:txtObj];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [QQApiInterface sendReq:req];
        });
    }else {
        
        QQApiTextObject *txtObj = [QQApiNewsObject objectWithURL:[NSURL URLWithString:url] title:title description:content previewImageURL:[NSURL URLWithString:imgUrl]];
        
        SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:txtObj];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [QQApiInterface SendReqToQZone:req];
        });
    }
    
}

@end
